/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
  let result = [];
  nums.forEach((n) => {
    if (result.length === 0) {
      result = [ [ n ] ];
    } else {
      const t = [];
      for (let i = 0; i < result.length; i++) {
        const item = result[i];
        t.push(...jump(item, n));
      }
      result = t;
    }
  });
  return result;
};

function jump(li, e) {
  const r = [];
  for (let i = 0; i <= li.length; i++) {
    const p = li.slice(0, i);
    const v = li.slice(i, li.length);
    p.push(e);
    p.push(...v);
    r.push(p);
  }
  return r;
}
const perms = permute([ 1, 2, 3, 4, 5, 6, 7 ]).map((r) => r.join('')).sort();

console.log(JSON.stringify(perms, null, '    '));
